import _ from 'lodash';
import { message } from 'antd';
import {
    getStoreInfo,
    createStore,
    updateStore
} from '../../services/store';

const areaDataOrigin = require('../../assets/areaData.json');

const A_FIX = 'pro_';
const B_FIX = 'city_';
const C_FIX = 'id_';

const normalizeArea = (areaData, key) => {
    if (!areaData || areaData.length < 1) {
        return false;
    }
    const self = key;
    let next = null;
    let isLeaf = false;
    let codeKey;
    let proFix;
    let pidKey;
    switch (key) {
        case 'a':
            next = 'b';
            codeKey = 'ProID';
            proFix = A_FIX;
            break;
        case 'b':
            next = 'c';
            codeKey = 'CityID';
            pidKey = 'ProID';
            proFix = B_FIX;
            break;
        case 'c':
            isLeaf = true;
            codeKey = 'Id';
            pidKey = 'CityID';
            proFix = C_FIX;
            break;
    }
    return _.map(areaData, (area, i) => {
        const { name: label } = area;
        return {
            label,
            value: `${proFix}${area[codeKey]}`,
            code: `${area[codeKey]}`,
            pid: `${pidKey && area[pidKey]}`,
            self,
            next,
            isLeaf,
            i,
        };
    });
};

const initOptions = (initialValue) => {
    const rootList = normalizeArea(areaDataOrigin.a, 'a');
    if (!_.isArray(initialValue) || (!initialValue || initialValue.length < 2)) {
        return rootList;
    }
    const [a, b] = initialValue;
    const aCode = a.replace(A_FIX, '');
    const bCode = b.replace(B_FIX, '');
    const bList = normalizeArea(
        _.filter(areaDataOrigin.b, (ad) => {
            return ad.ProID === parseInt(aCode, 10);
        }),
        'b'
    );
    _.find(bList, ['code', bCode]).children = normalizeArea(
        _.filter(areaDataOrigin.c, (ad) => {
            return ad.CityID === parseInt(bCode, 10);
        }),
        'c'
    );
    _.find(rootList, ['code', aCode]).children = bList;
    return rootList;
};

export default {
    namespace: 'store',
    state: {
        data: null,
        editorData: null,
        areaData: normalizeArea(areaDataOrigin.a, 'a'),
        viewType: 0,
    },
    subscriptions: {
        setup(args) {
            const { dispatch, history } = args;
            history.listen(({ pathname }) => {
                switch (pathname) {
                    case '/store':
                    case '/store/info': {
                        dispatch({
                            type: 'init',
                        });
                        break;
                    }
                }
            });
        }
    },
    effects: {
        * init(payload, { put, call}) {
            const { code, data, msg } = yield call(getStoreInfo);
            if (code === 1) {
                console.log(data);
                let { area } = data || {};
                //TODO 地区数据需要从字符串改为数组，服务端返回数据要修改
                if (!_.isArray(area)) {
                    area = area.replace(/"/g, '').replace(/\[|\]/g, '').split(',');
                }
                const areaData = initOptions(area);
                data.area = area;
                yield put({
                    type: 'setState',
                    payload: {
                        data,
                        editorData: data,
                        viewType: 0,
                        areaData,
                    },
                });
            } else {
                message.error(msg);
            }
            // const { data } = yield select((state => state.store));
            // const { user } = yield select((state => state.app));
            // if (!data || data.id.toString() !== user.storeId) {
            //     const { code, data, msg } = yield call(getStoreInfo);
            //     if (code === 1) {
            //         let { area } = data || {};
            //         //TODO 地区数据需要从字符串改为数组，服务端返回数据要修改
            //         if (!_.isArray(area)) {
            //             area = area.replace(/"/g, '').replace(/\[|\]/g, '').split(',');
            //         }
            //         const areaData = initOptions(area);
            //         data.area = area;
            //         yield put({
            //             type: 'setState',
            //             payload: {
            //                 data,
            //                 editorData: data,
            //                 viewType: 0,
            //                 areaData,
            //             },
            //         });
            //     } else {
            //         message.error(msg);
            //     }
            // } else {
            //     yield put({
            //         type: 'setState',
            //         payload: {
            //             viewType: 0,
            //         },
            //     });
            // }
        },
        * initEditor({ payload: { editorData, viewType } }, { put }) {
            yield put({
                type: 'setState',
                payload: {
                    viewType,
                    editorData
                },
            });
        },
        * areaLoad({ payload: { next, code, pid, i } }, { put, select }) {
            const { areaData } = yield select(state => state.store);
            const children = _.filter(
                areaDataOrigin[next],
                ({ ProID, CityID }) => {
                    if (next === 'b') {
                        return code.toString() === ProID.toString();
                    }
                    return code.toString() === CityID.toString();
                });
            if (next === 'b') {
                _.set(areaData, `[${i}].children`, normalizeArea(children, next));
            } else if (next === 'c') {
                _.find(areaData, ['code', pid]).children[i].children = normalizeArea(children, next);
            }
            yield put({
                type: 'setState',
                payload: { areaData },
            });
        },
        * editStore({ payload }, { put, call, select }) {
            const { id: masterId } = yield select(state => state.app.user);
            let res;
            if (payload.id || payload.storeId) {
                res = yield call(updateStore, {
                    ...payload,
                    masterId,
                });
            } else {
                res = yield call(createStore, {
                    ...payload,
                    masterId,
                });
            }
            if (res.code === '0000') {
                yield put({
                    type: 'setState',
                    payload: {
                        viewType: 0,
                    },
                });
                message.success(res.msg);
            } else {
                message.error(res.msg);
            }
        },
    },
    reducers: {
        upEditors(state, { payload }) {
            _.each(payload, ({ value }, k) => {
                _.set(state, `editorData.${k}`, value);
            });
            return state;
        },
        setState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
    }
};
